package com.googlesource.gerrit.plugins.examples.servlet.export;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gerrit.extensions.annotations.PluginCanonicalWebUrl;
import com.google.gerrit.extensions.annotations.PluginName;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.googlesource.gerrit.plugins.examples.servlet.HttpClientUtil;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Singleton
public class ExportServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final Logger log = LoggerFactory.getLogger(ExportServlet.class);

    @Inject
    ExportServlet(@PluginName String pluginName, @PluginCanonicalWebUrl String url) {
        log.info(String.format("Cookbook Plugin '%s' at url %s", pluginName, url));
    }

    @Override
    protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
            throws IOException, ServletException {
        // 空占位符
        final String EMPTY_PLACEHOLDER = "-";
        log.info("request.getParameter('q')={}", request.getParameter("q"));
        // 获取结果
        String result = HttpClientUtil
                .sendGet("changes/?o=LABELS&o=DETAILED_ACCOUNTS&q=" + request.getParameter("q"),
                        request)
                .substring(4)
                .trim();
        log.info("result:{}", result);
        // 解析内容
        List<JSONObject> lists = JSON.parseArray(result, JSONObject.class);
        List<ExcelExportInfo> excelInfos = new ArrayList<>();
        for (JSONObject info : lists) {
            ExcelExportInfo excelInfo = new ExcelExportInfo();
            excelInfo.setSubject(info.getString("subject") != null ? info.getString("subject")
                    : EMPTY_PLACEHOLDER);
            excelInfo.setProject(info.getString("project") != null ? info.getString("project")
                    : EMPTY_PLACEHOLDER);
            excelInfo.setStatus(info.getString("status") != null ? info.getString("status")
                    : EMPTY_PLACEHOLDER);
            excelInfo.setOwner(
                    info.get("owner") != null ? info.getJSONObject("owner").getString("name")
                            : EMPTY_PLACEHOLDER);
            excelInfo.setAssignee(
                    info.get("assignee") != null ? info.getJSONObject("assignee").getString("name")
                            : EMPTY_PLACEHOLDER);
            excelInfo.setBranch(info.getString("branch") != null ? info.getString("branch")
                    : EMPTY_PLACEHOLDER);
            excelInfo.setCreated(
                    info.getString("created") != null ? info.getString("created").substring(0, 19)
                            : EMPTY_PLACEHOLDER);
            excelInfo.setUpdated(
                    info.getString("updated") != null ? info.getString("updated").substring(0, 19)
                            : EMPTY_PLACEHOLDER);
            // size
            long insertions = info.getLongValue("insertions");
            long deletions = info.getLongValue("deletions");
            excelInfo.setSize(ChangeSizeBucket.getChangeSizeBucket(insertions + deletions));
            // how size works
            JSONObject labels = info.getJSONObject("labels");
            if (!isJsonEmpty(labels)) {
                // Code-Review
                JSONObject cr = labels.getJSONObject("Code-Review");
                excelInfo.setCodeReview(!isJsonEmpty(cr));
                // Non-Author-Code-Review
                JSONObject nacr = labels.getJSONObject("Non-Author-Code-Review");
                excelInfo.setNonAuthorCodeReview(!isJsonEmpty(nacr));
                // Verified
                JSONObject verified = labels.getJSONObject("Verified");
                excelInfo.setVerified(!isJsonEmpty(verified));
            }
            excelInfos.add(excelInfo);
        }
        String[] titleColumn = {
                "project",
                "subject",
                "status",
                "owner",
                "assignee",
                "branch",
                "created",
                "updated",
                "size",
                "codeReview",
                "nonAuthorCodeReview",
                "verified"
        };
        String[] titleName = {
                "Repository",
                "subject",
                "Status",
                "Owner",
                "Assignee",
                "Branch",
                "Created",
                "Updated",
                "Size",
                "CR",
                "NACR",
                "V"
        };
        int[] titleSize = {40, 60, 10, 20, 20, 15, 20, 20, 10, 10, 10, 10};
        ExcelExportUtil excelExport = new ExcelExportUtil(response, "Gerrit导出信息(共" + excelInfos.size() + "条数据)", "sheet1",
                titleColumn.length - 1);
        excelExport.writeExcel(titleColumn, titleName, titleSize, excelInfos);
    }

    @Override
    protected void doPost(final HttpServletRequest req, final HttpServletResponse rsp)
            throws IOException, ServletException {

    }

    private boolean isJsonEmpty(JSONObject json) {
        return json == null || json.isEmpty();
    }

}